package com.mxx.common.observer;

import android.app.Activity;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.mxx.basic.server.retrofit.observer.StringObserver;
import com.mxx.basic.utils.ToastUtils;
import com.mxx.common.response.BaseEntityResponse;

import okhttp3.ResponseBody;
import retrofit2.Response;

/**
 * 作者：刘江飞
 * 时间：2020/9/2  14:32
 * 邮箱：642371742Z@qq.com
 * 描述：
 **/
public abstract class CommonObserver extends StringObserver {

    public CommonObserver(Activity mActivity) {
        super(mActivity);
    }

    public CommonObserver(boolean isShowLoading, Activity mActivity) {
        super(mActivity);
        this.isShowLoading = isShowLoading;
    }

    @Override
    public void onNext(Response<ResponseBody> response) {
        super.onNext(response);
    }

    @Override
    protected void onSuccess(String originalJson) {
        mLogger.json("原始已包装的数据({code:1,message:消息,data{}})：" + originalJson);
        if ("".equals(originalJson)) {
            handlerJsonData(originalJson);
            return;
        }
        BaseEntityResponse response = null;
        try {
            response = new Gson().fromJson(originalJson, new TypeToken<BaseEntityResponse>() {
            }.getType());
        } catch (JsonSyntaxException e) {
            e.printStackTrace();
        }
        if (response == null) {
            onFailed(1, "");
            return;
        }
        if (response.code != 0) {
            if (response.code == 301) {
                onFailed(response);
                return;
            }
            onFailed(response.code, response.tip);
            return;
        }
        GsonBuilder gsonbuilder = new GsonBuilder();
        gsonbuilder.serializeNulls();
        Gson gson = gsonbuilder.create();
        String json = gson.toJson(response.data);
        mLogger.i(mActivity.getClass().getName(), json);
        if ("".equals(json)) {
            onFailed(-1, "数据为空");
            return;
        }
        handlerJsonData(json);
    }


    protected abstract void handlerJsonData(String json);

    @Override
    protected void onFailed(boolean showToast, int code, String msg) {
        super.onFailed(showToast, code, msg);
        ToastUtils.showToast(mActivity, msg);
    }

    protected void onFailed(BaseEntityResponse response) {

    }
}
